package com.vilen.cms.web;

import com.vilen.cms.model.CmsException;
import com.vilen.cms.model.User;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Set;

/**
 * Created by vilen on 2017/2/16.
 */
public class AuthInterceptor extends HandlerInterceptorAdapter{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //System.out.println(handlerMethod.getBean().getClass().getName() + "." + handlerMethod.getMethod().getName());
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            response.sendRedirect(request.getContextPath()+"/login");
        }else {
            boolean isAdmin = (Boolean) session.getAttribute("isAdmin");
            if (!isAdmin) {
                // 不是超级管理人员
                Set<String> actions = (Set<String>) session.getAttribute("allActions");
                String aname = handlerMethod.getBean().getClass().getName() + "." + handlerMethod.getMethod().getName();
                if (!actions.contains(aname)) {
                    throw new CmsException("没有权限访问该功能");
                }
            }
        }
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}
